package com.wlient.basic.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


public class BeanUtil {

//    类相同字段复制

    public static <T> T copyProperties(Class<T> clazz, Object source) {
        if (source == null) {
            return null;
        } else {
            T t = null;
            try {
                t = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            BeanUtils.copyProperties(source, t);
            return t;
        }

    }

    public static <T> List<T> copyProperties(Class<T> clazz, Collection<?> collection) {
        return CollectionUtils.isEmpty(collection) ? Collections.emptyList() : (List) collection.stream().map((o) -> {
            return copyProperties(clazz, o);
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    private BeanUtil() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }
}